<template>
	<view class="wrap">
		<view class="content">
			<view class="item" style="padding: 12rpx 48rpx;" v-if="type == 2">
				<u--form labelWidth="200rpx" :labelStyle="{color: '#333333', fontSize: '30rpx'}">
					<u-form-item label="线路名称" borderBottom required>
						<u--input v-model="model.userCode" border="none" placeholder="请输入名称"></u--input>
					</u-form-item>
					<u-form-item label="所属项目" @click="showProject = true" required>
						<u--input v-model="nameProject" border="none" placeholder="点击选择项目" suffixIcon="arrow-right"
							suffixIconStyle="color: #c0c4cc" disabled disabledColor="#fff"></u--input>
					</u-form-item>
				</u--form>
			</view>
			<view class="item">
				<u--form labelWidth="200rpx" :labelStyle="{color: '#333333', fontSize: '30rpx'}">
					<u-form-item label="托运人单位" borderBottom required>
						<u--input v-model="model.companyName" border="none" placeholder="请输入托运人单位"></u--input>
					</u-form-item>
					<u-form-item label="托运人姓名" borderBottom>
						<u--input v-model="model.consignee" border="none" placeholder="请输入托运人姓名"></u--input>
					</u-form-item>
					<u-form-item label="联系电话" borderBottom required>
						<u--input v-model="model.tel" type="number" border="none" placeholder="请输入联系电话"></u--input>
					</u-form-item>
					<u-form-item label="取货城市" borderBottom @click="showRegion1 = true" required>
						<u--input v-model="valueRegion1" border="none" placeholder="请选择所在地区" suffixIcon="arrow-right"
							suffixIconStyle="color: #c0c4cc" disabled disabledColor="#fff"></u--input>
					</u-form-item>
					<u-form-item label="详细地址" @click="onShowMap(1)">
						<u--input v-model="model.addressDetail" disabled disabledColor="#fff" border="none" placeholder="请输入详细地址" suffixIcon="map"></u--input>
					</u-form-item>
					<!-- <textarea placeholder-style="color:#c0c4cc" placeholder-class="placeholder"
						placeholder="粘贴信息，自动拆分托运人单位、电话和地址" /> -->
				</u--form>
			</view>
			<view class="item">
				<u--form labelWidth="200rpx" :labelStyle="{color: '#333333', fontSize: '30rpx'}">
					<u-form-item label="收货人单位" borderBottom required>
						<u--input v-model="model.tcompanyName" border="none" placeholder="请输入收货人单位"></u--input>
					</u-form-item>
					<u-form-item label="收货人姓名" borderBottom>
						<u--input v-model="model.tconsignee" border="none" placeholder="请输入收货人姓名"></u--input>
					</u-form-item>
					<u-form-item label="联系电话" borderBottom required>
						<u--input v-model="model.ttel" type="number" border="none" placeholder="请输入联系电话"></u--input>
					</u-form-item>
					<u-form-item label="收货城市" borderBottom @click="showRegion2 = true" required>
						<u--input v-model="valueRegion2" border="none" placeholder="请选择所在地区" suffixIcon="arrow-right"
							suffixIconStyle="color: #c0c4cc" disabled disabledColor="#fff"></u--input>
						</u--input>
					</u-form-item>
					<u-form-item label="详细地址" @click="onShowMap(2)">
						<u--input v-model="model.taddressDetail" disabled disabledColor="#fff" border="none" placeholder="请输入详细地址" suffixIcon="map"></u--input>
					</u-form-item>
					<!-- 	<textarea placeholder-style="color:#c0c4cc" placeholder-class="placeholder"
						placeholder="粘贴信息，自动拆分托运人单位、电话和地址" /> -->
				</u--form>
				<!-- <view class="check">
					<u-checkbox-group activeColor="#00468C">
						<u-checkbox v-model="checked" shape="circle" label="保存路线"></u-checkbox>
					</u-checkbox-group>
				</view> -->
			</view>
		</view>
		<view class="bottom-wrap">
			<view v-if="type == 2" class="submit" @click="postAddLine">保存</view>
			<view v-if="type == 1" class="submit" @click="saveLine">使用线路</view>
		</view>

		<u-picker :show="showRegion1" ref="uPicker1" :columns="columns1" :defaultIndex="defaultIndex1" keyName="label"
			@confirm="confirm1" @change="changeHandler1" closeOnClickOverlay @close="showRegion1 = false"
			@cancel="showRegion1 = false"></u-picker>

		<u-picker :show="showRegion2" ref="uPicker2" :columns="columns2" :defaultIndex="defaultIndex2" keyName="label"
			@confirm="confirm2" @change="changeHandler2" closeOnClickOverlay @close="showRegion2 = false"
			@cancel="showRegion2 = false"></u-picker>

		<!-- 弹出层 -->
		<u-popup :show="showProject" @close="cancelProject" :round="10">
			<view class="popup-wrap">
				<view class="title">选择项目</view>
				<view class="popup-empty" v-if="!listProject.length">暂无数据～～～</view>
				<view class="popup-list" v-else>
					<u-radio-group v-model="valueProjectCache" placement="column" iconPlacement="right"
						activeColor="#00468C" @change="changeProject">
						<view class="item1" v-for="(item, index) in listProject" :key="index">
							<u-radio :label="item.project_name" :name="item.project_id"></u-radio>
						</view>
					</u-radio-group>
				</view>
				<view class="popup-btn">
					<view class="cancel btn" @click="cancelProject">取消</view>
					<view class="confirm btn" @click="confirmProject">确认</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import {type} from '@/utils/type.js'
	import {
		addLine,
		getRegion,
		getAllReject
	} from '@/config/api/app.js'
	// import address from '@/utils/area'
	import {
		mapGetters,
		mapMutations
	} from 'vuex'
	export default {
		data() {
			return {
				type: '',	// 1是编辑，2是新建线路
				info: null,
				model: {
					userCode: '',
					companyName: '',
					consignee: '',
					tel: '',
					region: [],
					province: '',
					city: '',
					county: '',
					addressDetail: '',
					tcompanyName: '',
					tconsignee: '',
					ttel: '',
					tregion: [],
					tprovince: '',
					tcity: '',
					tcounty: '',
					taddressDetail: '',
					postCode: '',
					tpostCode: '',
					projectName: '',
					faddressId: '',
					taddressId: '',
					shippingLng: null,
					shippingLat: null,
					receiptLng: null,
					receiptLat: null,
				},
				valueRegion1: '',
				valueRegion2: '',

				// 项目
				listProject: null,
				showProject: false,
				listProject: [],
				nameProject: '',
				valueProject: '',
				valueProjectCache: '', //	项目选择缓存

				showRegion1: false,
				defaultIndex1: [0, 0, 0],
				columns1: [], //省份数据显示，三级联动需要三维数组，展示初始数据
				columnData1: [], //市数据
				columnDatas1: [], //区地址

				showRegion2: false,
				defaultIndex2: [0, 0, 0],
				columns2: [], //省份数据显示，三级联动需要三维数组，展示初始数据
				columnData2: [], //市数据
				columnDatas2: [], //区地址
			}
		},
		onLoad(options) {
			this.type = options.type
			if(options.info){
				this.info = JSON.parse(options.info)
				console.log(this.info)
				if(!this.info.shippingLng && !this.info.shippingLat){
					uni.request({
						url: 'https://restapi.amap.com/v3/geocode/geo?parameters',
						method: 'GET',
						data: {
							key: type.mapKey,
							address: `${this.info.shippingCity}${this.info.shippingAddress}`
						},
						success: res => {
							let latitude = res.data.geocodes[0].location.split(',')[1]
							let longitude = res.data.geocodes[0].location.split(',')[0]
							this.model.shippingLng = longitude
							this.model.shippingLat = latitude
						}
					})
				}else{
					this.model.shippingLng = this.info.shippingLng
					this.model.shippingLat = this.info.shippingLat
				}
				if(!this.info.receiptLng && !this.info.receiptLat){
					uni.request({
						url: 'https://restapi.amap.com/v3/geocode/geo?parameters',
						method: 'GET',
						data: {
							key: type.mapKey,
							address: `${this.info.receiptCity}${this.info.receiptAddress}`
						},
						success: res => {
							let latitude = res.data.geocodes[0].location.split(',')[1]
							let longitude = res.data.geocodes[0].location.split(',')[0]
							this.model.receiptLng = longitude
							this.model.receiptLat = latitude
						}
					})
				}else{
					this.model.receiptLng = this.info.receiptLng
					this.model.receiptLat = this.info.receiptLat
				}
				this.model.companyName = this.info.shippingUserUnit
				this.model.tel = this.info.shippingUserTel
				this.model.consignee = this.info.shippingUserName
				this.model.addressDetail = this.info.shippingAddress
				this.model.province = this.info.sprovince
				this.model.city = this.info.scity
				this.model.county = this.info.scounty
				this.model.region = this.info.shippingCity.match(/.+?(省|市|特别行政区|自治区|自治州|县|区|岛|城)/g)
				this.valueRegion1 = this.model.region.join(' ')
				
				this.model.tcompanyName = this.info.receiptUserUnit
				this.model.ttel = this.info.receiptUserTel
				this.model.tconsignee = this.info.receiptUserName
				this.model.taddressDetail = this.info.receiptAddress
				this.model.tprovince = this.info.rprovince
				this.model.tcity = this.info.rcity
				this.model.tcounty = this.info.rcounty
				this.model.tregion = this.info.receiptCity.match(/.+?(省|市|特别行政区|自治区|自治州|县|区|岛|城)/g)
				this.valueRegion2 = this.model.tregion.join(' ')
			}
			if(this.type == 2){
				this.getProject()
			}
			this.initDataPicker() //初始化省份列表
		},
		onShow() {
			if(this.saveDetail01){
				this.model.addressDetail = this.saveDetail01.address
				this.model.shippingLng = this.saveDetail01.longitude
				this.model.shippingLat = this.saveDetail01.latitude
			}
			if(this.saveDetail02){
				this.model.taddressDetail = this.saveDetail02.address
				this.model.receiptLng = this.saveDetail02.longitude
				this.model.receiptLat = this.saveDetail02.latitude
			}
		},
		beforeDestroy() {
			this.SAVEDETAIL01(null)
			this.SAVEDETAIL02(null)
		},
		methods: {
			...mapMutations(['SELECTADDRESS', 'SAVEDETAIL01', 'SAVEDETAIL02']),
			saveLine() {
				let {
					userCode,
					companyName,
					tel,
					region,
					tcompanyName,
					ttel,
					tregion,
				} = this.model
				if (!companyName) {
					uni.$u.toast('请输入托运单位');
					return
				}
				if (!tel) {
					uni.$u.toast('请输入托运人电话');
					return
				}
				if (!uni.$u.test.mobile(tel)) {
					uni.$u.toast('托运电话格式不正确，请重新输入');
					return
				}
				if (!region.length) {
					uni.$u.toast('请选择取货城市');
					return
				}
				if (!tcompanyName) {
					uni.$u.toast('请输入收货单位');
					return
				}
				if (!ttel) {
					uni.$u.toast('请输入收货人电话');
					return
				}
				if (!uni.$u.test.mobile(ttel)) {
					uni.$u.toast('取货电话格式不正确，请重新输入');
					return
				}
				if (!tregion.length) {
					uni.$u.toast('请选择收货城市');
					return
				}
				let item = {
					fAddressDetail: this.model.addressDetail,
					fCity: this.valueRegion1.replace(/\s+/g, ''),
					fCityValue: this.model.county,
					fCompanyName: this.model.companyName,
					fConsignee: this.model.consignee,
					fTel: this.model.tel,
					tAddressDetail: this.model.taddressDetail,
					tCity: this.valueRegion2.replace(/\s+/g, ''),
					tCityValue: this.model.tcounty,
					tCompanyName: this.model.tcompanyName,
					tConsignee: this.model.tconsignee,
					tTel: this.model.ttel,
					shippingLng: this.model.shippingLng,
					shippingLat: this.model.shippingLat,
					receiptLng: this.model.receiptLng,
					receiptLat: this.model.receiptLat
				}
				console.log(this.valueRegion1.replace(/\s+/g, ''))
				console.log(this.valueRegion2.replace(/\s+/g, ''))
				this.SELECTADDRESS(item)
				uni.navigateBack()
			},
			//	线路保存提交
			postAddLine() {
				let obj = Object.assign(this.model, {
					projectId: this.valueProject
				})
				let {
					userCode,
					companyName,
					tel,
					region,
					tcompanyName,
					ttel,
					tregion,
					projectId
				} = obj
				console.log(obj)
				if (!userCode) {
					uni.$u.toast('请输入线路名称');
					return
				}
				if (!projectId) {
					uni.$u.toast('请先选择项目');
					return
				}
				if (!companyName) {
					uni.$u.toast('请输入托运单位');
					return
				}
				if (!tel) {
					uni.$u.toast('请输入托运人电话');
					return
				}
				if (!uni.$u.test.mobile(tel)) {
					uni.$u.toast('托运电话格式不正确，请重新输入');
					return
				}
				if (!region.length) {
					uni.$u.toast('请选择取货城市');
					return
				}
				if (!tcompanyName) {
					uni.$u.toast('请输入收货单位');
					return
				}
				if (!ttel) {
					uni.$u.toast('请输入收货人电话');
					return
				}
				if (!uni.$u.test.mobile(ttel)) {
					uni.$u.toast('取货电话格式不正确，请重新输入');
					return
				}
				if (!tregion.length) {
					uni.$u.toast('请选择收货城市');
					return
				}
				addLine(obj, {
					custom: {
						title: '提交中……'
					}
				}).then((res) => {
					if (res.code == 0) {
						console.log(res)
						uni.$u.toast('添加成功');
						setTimeout(() => {
							uni.navigateBack({
								delta: 2
							})
						}, 500)
					} else {
						uni.$u.toast(res.msg);
					}
				}).catch(err => {
					uni.$u.toast(err);
					console.log(err)
				})
			},
			// 项目
			changeProject(e) {
				this.valueProjectCache = e
			},
			cancelProject() {
				this.showProject = false
				this.valueProjectCache = this.valueProject
			},
			confirmProject() {
				this.showProject = false
				this.valueProject = this.valueProjectCache
				let obj = this.listProject.find(item => {
					return item.project_id === this.valueProject
				})
				this.nameProject = obj.project_name
			},
			onShowMap(type) {
				if(type == 1){
					if(!this.valueRegion1){
						uni.$u.toast('请先选择省市区');
					}else{
						uni.navigateTo({
							url: `/pages/waybill/map?type=${type}&&address=${this.valueRegion1}`
						})
					}
				}else{
					if(!this.valueRegion2){
						uni.$u.toast('请先选择省市区');
					}else{
						uni.navigateTo({
							url: `/pages/waybill/map?type=${type}&&address=${this.valueRegion2}`
						})
					}
				}
			},
			//	获取项目列表
			getProject() {
				let data = {
					params: {},
					custom: {
						title: '获取项目……'
					}
				}
				getAllReject(data).then((res) => {
					if (res.code == 0) {
						this.listProject = res.data.project
					} else {
						uni.$u.toast(res.msg);
					}
				}).catch(err => {
					console.log(err)
				})
			},
			confirm1(e) {
				console.log(e)
				this.model.region = []
				this.showRegion1 = false
				this.valueRegion1 = e.value[0].label + ' ' + e.value[1].label + ' ' + e.value[2].label
				this.defaultIndex1 = e.indexs
				e.value.forEach(item => {
					this.model.region.push(item.value)
				})
				this.model.province = e.value[0].value
				this.model.city = e.value[1].value
				this.model.county = e.value[2].value
			},
			confirm2(e) {
				this.model.tregion = []
				this.showRegion2 = false
				this.valueRegion2 = e.value[0].label + ' ' + e.value[1].label + ' ' + e.value[2].label
				this.defaultIndex2 = e.indexs
				e.value.forEach(item => {
					this.model.tregion.push(item.value)
				})
				this.model.tprovince = e.value[0].value
				this.model.tcity = e.value[1].value
				this.model.tcounty = e.value[2].value
			},
			newArrint(arr) {
				let newArr = [];
				for (let i = 0; i < arr.length; i++) {
					let arrLi = {};
					if (arr[i].children.length > 0) {
					    let arrchildren = arr[i].children;
						arrLi = arr[i];
						arrLi.children = [];
						for (let j = 0; j < arrchildren.length; j++) {
							if (arrchildren[j].children.length > 0) {
								arrLi.children.push(arrchildren[j]);
							}
						}
						newArr.push(arrLi);
					}
				}
				let convert = [];
				for (let z = 0; z < newArr.length; z++) {
					if (newArr[z].children.length > 0) {
						convert.push(newArr[z]);
					}
				}
				return convert;
			},
			initDataPicker() {
				getRegion().then(res => {
					if (res.code != 0) {
						uni.$u.toast(res.msg)
						return
					}
					let address = this.newArrint(res.data)
					let province = []; //初始数据需要展示的省份
					let province1 = []; //因为第一个市北京市，所以就直接添加北京市下辖的直辖市了 也即初始数据需要展示的市，北京市只有一个市辖区
					let province2 = []; //初始数据需要展示的区域数据，也即是 北京市市辖区内的区
					address.map(item => {
						province.push(item);
					});
					address[0].children.map(item => {
						province1.push(item);
					});
					address[0].children[0].children.map(item => {
						province2.push(item);
					});
					//省数据 因为要做数据初始化，所以是三维数组
					// 数据格式 [ [所有的省份数据:{},{}] , [第一个省份下的所有的市:{},{},{}] , [第一个市下面所有的区:{},{},{}] ]
					this.columns1.push(province);
					this.columns1.push(province1);
					this.columns1.push(province2);

					this.columns2.push(province);
					this.columns2.push(province1);
					this.columns2.push(province2);
					// 市数据数组，筛选address文件，将全国所有省下面的市数据放入数组
					// 格式[ [第一个省下面所有市,{},{},{}] , [第二个省下面所有市{},{},{}] , [第三个省下面所有市{},{},{}] ] 注意，以上的第一第二对应着 columns[0] 的数据
					address.map(item => {
						let city = [];
						item.children.map(item1 => {
							city.push(item1);
						});
						this.columnData1.push(city);
						this.columnData2.push(city);
					});
					//区数据数组
					//数据格式: [ 所有省下面所有市的所有区 [ 第一个省下面所有市的区:[ [第一个省下面第一个市的所有区] , [第一个省下面第二个市的所有区] ,]   ,   [ 第二个省下面所有市的区:[ [第二个省下面第一个市的所有区] , [第二个省下面第二个市的所有区] ,]   ]
					let area = [];
					address.map((item, index) => {
						let area1 = []; //省下面所有市的初始化
						item.children.map(item1 => {
							area = []; //市下面的区初始化
							item1.children.map(item2 => {
								area.push(item2);
							});
							area1.push(area); // 每循环一个市，添加该市下面的所有区
						});
						this.columnDatas1.push(area1); // 每循环一个省，添加该省下面的所有市
						this.columnDatas2.push(area1); // 每循环一个省，添加该省下面的所有市
					});
				}).catch(err => {
					console.log(err)
				})
			},
			changeHandler1(e) { //城市选择时触发
				const {
					columnIndex, //当前选择的列，省 / 市 / 区
					value, // 当前选择的数组内容
					values, // values为当前变化列的数组内容
					index, // 当前列的下标值
					indexs, // 当前选择 省 市 区的下表值
					picker = this.$refs.uPicker1
				} = e;
				// 当第一列值发生变化时，变化第二列和第三列的值（省份变更，市和区跟着变更）
				if (columnIndex === 0) { // 判断当前变更的是省还是市还是区
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.columnData1[
						index]); //设置市为该省下面的所有市，index是当前省在省份数组的下标，对应市数组中的下表就是 该省下面的所有市 的数据
					picker.setColumnValues(2, this.columnDatas1[index][0]); // 设置区域为该省下面第一个市下面的所有区域
				}
				if (columnIndex === 1) {
					// 当第二列发生变化 变化对应的第三列 
					picker.setColumnValues(2, this.columnDatas1[indexs[0]][index]); //同上
				}
			},
			changeHandler2(e) { //城市选择时触发
				const {
					columnIndex, //当前选择的列，省 / 市 / 区
					value, // 当前选择的数组内容
					values, // values为当前变化列的数组内容
					index, // 当前列的下标值
					indexs, // 当前选择 省 市 区的下表值
					picker = this.$refs.uPicker2
				} = e;
				// 当第一列值发生变化时，变化第二列和第三列的值（省份变更，市和区跟着变更）
				if (columnIndex === 0) { // 判断当前变更的是省还是市还是区
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.columnData2[
						index]); //设置市为该省下面的所有市，index是当前省在省份数组的下标，对应市数组中的下表就是 该省下面的所有市 的数据
					picker.setColumnValues(2, this.columnDatas2[index][0]); // 设置区域为该省下面第一个市下面的所有区域
				}
				if (columnIndex === 1) {
					// 当第二列发生变化 变化对应的第三列 
					picker.setColumnValues(2, this.columnDatas2[indexs[0]][index]); //同上
				}
			},
		},
		computed: {
			...mapGetters(['saveDetail01', 'saveDetail02'])
		},
	}
</script>

<style lang="scss">
	page {
		background: #FAFAFA;
	}

	.wrap {
		width: 100vw;
		height: 100vh;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		box-sizing: border-box;

		.content {
			width: 100%;
			overflow: auto;
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: calc(90rpx + env(safe-area-inset-bottom));
		}
	}

	.popup-wrap {
		padding: 32rpx;

		.popup-empty {
			text-align: center;
			color: #c0c4cc;
			font-size: 30rpx;
			padding: 32rpx 0;
		}

		.title {
			text-align: center;
			font-size: 32rpx;
			font-weight: 500;
			color: #333333;
			margin-bottom: 24rpx;
		}
		.line-title{
			display: flex;
			justify-content: space-between;
			font-size: 32rpx;
			font-weight: 500;
			color: #333333;
			padding-bottom: 12rpx;
			.text{
				text-align: center;
				flex: 1;
			}
			.cancel-btn{
				font-weight: 400;
			}
			.add-btn{
				color: #00468C;
			}
		}
		.popup-btn {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 12rpx 0 calc(12rpx + env(safe-area-inset-bottom));

			.btn {
				font-size: 30rpx;
				font-weight: 500;
				line-height: 80rpx;
				border-radius: 12rpx;
				text-align: center;
				box-shadow: 0 0 20rpx 12rpx rgba(0, 62, 129, 0.04);
				box-sizing: border-box;
			}

			.cancel {
				color: #333333;
				width: 40%;
				background: #fff;
				border: 1rpx solid #e9e9e9;
			}

			.confirm {
				width: 55%;
				color: #FFFFFF;
				background: linear-gradient(to right, #4d83b9, #003E81);
			}
		}

		.popup-list {
			max-height: 460rpx;
			box-sizing: border-box;
			overflow: auto;
			margin: 12rpx 0;

			.item1 {
				border-bottom: 1rpx solid #F5F7FB;

				.u-radio {
					padding: 24rpx 0;
				}

				&:last-child {
					border-bottom: none;
				}
			}
		}
	}

	.wrap {
		// padding: 32rpx 0;
	}

	.item {
		padding: 12rpx 48rpx 32rpx;
		margin-top: 16rpx;
		background: #fff;

		textarea {
			padding: 24rpx;
			border-radius: 8rpx;
			border: 1rpx solid #c0c4cc;
			height: 150rpx;
			margin-top: 6rpx;
		}

		.check {
			margin-top: 32rpx;
		}
	}

	.placeholder {
		font-size: 30rpx;
		font-weight: 400;
		color: #c0c4cc;
	}

	.bottom-wrap {
		position: absolute;
		left: 0;
		bottom: calc(10rpx + env(safe-area-inset-bottom));
		width: 100vw;
		padding: 0 32rpx;
		box-sizing: border-box;

		.submit {
			width: 100%;
			font-size: 30rpx;
			font-weight: 500;
			color: #FFFFFF;
			line-height: 80rpx;
			border-radius: 12rpx;
			text-align: center;
			background: linear-gradient(to right, #4d83b9, #003E81);
		}
	}
</style>
